<template>
    <view class="dynamic-technician-add">
        <!-- <back></back> -->
        <view
            class="flex padding-lr-30 padding-top-60 padding-bottom-30"
            @click="is_cate_show = true"
        >
            <view class="text-30">分类</view>
            <view class="text-30 flex-one text-right">{{
                catename ? catename : "请选择分类"
            }}</view>
        </view>
        <picker :range="shoplist" range-key="title" @change="choseShop">
            <view class="flex padding-30">
                <view class="text-30">商品</view>
                <view class="text-30 flex-one text-right margin-left-30">{{
                    shopname ? shopname : "请选择商品"
                }}</view>
            </view>
        </picker>
        <view class="pd-lg">
            <view class="pb-md" :class="[{ 'flex-warp': subForm.type == 2 }]">
                <view class="mr-md" v-if="subForm.type == 2">
                    <upload
                        @upload="imgUpload"
                        @del="imgUpload"
                        :imagelist="subForm.cover"
                        filetype="picture"
                        imgtype="cover"
                        text="上传封面"
                        :imgsize="1"
                    >
                    </upload>
                </view>
                <upload
                    @upload="imgUpload"
                    @del="imgUpload"
                    :imagelist="subForm.imgs"
                    :filetype="subForm.type == 1 ? 'picture' : 'video'"
                    imgtype="imgs"
                    :text="subForm.type == 1 ? '上传图片' : '上传视频'"
                    :imgsize="subForm.type == 1 ? 9 : 1"
                >
                </upload>
            </view>
            <view class="space-md"></view>
            <input
                v-model="subForm.title"
                class="f-mini-title c-title"
                type="text"
                placeholder="填写标题有更多赞哟~"
                placeholder-class="f-mini-title c-caption"
                maxlength="10"
            />
            <view class="space-lg b-1px-b"></view>
            <view class="space-lg"></view>
            <textarea
                v-model="subForm.text"
                class="textarea f-desc c-title"
                maxlength="400"
                placeholder="还有更多的想法也一起写到正文吧~"
                placeholder-class="f-desc c-caption"
            ></textarea>
        </view>
        <view @tap.stop="toChooseLocation" class="pt-lg pl-lg pr-md flex-center f-desc">
            <i class="iconfont icon-dingwei"></i>
            <view class="flex-1 ml-sm mr-lg c-title ellipsis-2">
                {{ subForm.lat ? subForm.address : "添加地点" }}
            </view>
            <i class="iconfont icongengduo"></i>
        </view>
        <view class="space-max-footer"></view>
        <fix-bottom-button
            @confirm="submit"
            :text="[{ text: subForm.id ? '编辑动态' : '发布动态', type: 'confirm' }]"
            bgColor="#fff"
        >
        </fix-bottom-button>
        <!-- 多列选择 -->
        <view class="layer" v-if="is_cate_show" style="z-index: 9999999999">
            <view class="layer-content">
                <view
                    class="confirm-bar line-height-80 padding-lr-30 bg-ff border-bottom-ed flex align-center justify-between"
                >
                    <view class="text-cc" @click="is_cate_show = false">取消</view>
                    <view class="" style="color: #007aff" @click="cateSubmit()">确定</view>
                </view>
                <picker-view
                    :value="multiIndex"
                    :indicator-style="indicatorStyle"
                    class="picker-view"
                    @change="change"
                >
                    <picker-view-column>
                        <view
                            class="item-pircker"
                            v-for="(item, index) in catelist1"
                            :key="index"
                            >{{ item.title }}</view
                        >
                    </picker-view-column>
                    <picker-view-column v-if="catelist2">
                        <view
                            class="item-pircker"
                            v-for="(item, index) in catelist2"
                            :key="index"
                            >{{ item.title }}</view
                        >
                    </picker-view-column>
                </picker-view>
            </view>
        </view>
    </view>
</template>

<script>
import { mapState, mapActions, mapMutations } from "vuex";
export default {
    data() {
        return {
            options: {},
            subForm: {
                id: 0,
                cover: [],
                imgs: [],
                type: 1,
                title: "",
                text: "",
                lat: "",
                lng: "",
                address: "",
            },
            rule: [
                {
                    name: "cover",
                    checkType: "isNotNull",
                    errorMsg: "请上传封面图",
                },
                {
                    name: "imgs",
                    checkType: "isNotNull",
                    errorMsg: "",
                },
                {
                    name: "title",
                    checkType: "isNotNull",
                    errorMsg: "请输入标题",
                    regType: 2,
                },
                {
                    name: "text",
                    checkType: "isNotNull",
                    errorMsg: "请输入正文内容",
                    regType: 2,
                },
                {
                    name: "address",
                    checkType: "isNotNull",
                    errorMsg: "请选择定位地点",
                },
            ],
            lockTap: false,
            cate_id: "",
            multiIndex: [0, 0, 0],
            multiArray: [],
            indicatorStyle: "height: 80rpx;",
            catelist1: [],
            catelist2: [],
            is_cate_show: false,
            catename: "",
            shoplist: [],
            shopname: "",
            shopid: "",
        };
    },
    computed: mapState({
        primaryColor: (state) => state.config.configInfo.primaryColor,
        subColor: (state) => state.config.configInfo.subColor,
        configInfo: (state) => state.config.configInfo,
        userInfo: (state) => state.user.userInfo,
        location: (state) => state.user.location,
        haveShieldOper: (state) => state.user.haveShieldOper,
    }),
    onLoad(options) {
        let { type } = options;
        type = type * 1;
        this.options = options;
        this.subForm.type = type;
        this.rule[1].errorMsg = type == 1 ? "请上传图片" : "请上传视频";
        this.initIndex();
        this.$util.setNavigationBarColor({
            bg: this.primaryColor,
        });
    },
    onReady() {
        uni.request({
            url: "https://same.ascetic.top/index.php?i=666&m=longbing_massages_city&s=massage/app/Index/getCategory&urls=massage/app/Index/getCategory&cate_type=3&children=2",
            header: {
                autograph: uni.getStorageSync("autograph"),
            },
            success: (res) => {
                this.catelist1 = res.data.data;
                this.catelist2 = res.data.data[0].children;
            },
        });
        uni.request({
            url: "https://same.ascetic.top/api/shop/shop_goods_list",
            header: {
                autograph: uni.getStorageSync("autograph"),
                token: uni.getStorageSync("userInfo")["shop_token"],
            },
            data: {
                status: 0,
                audit: 2,
            },
            success: (res) => {
                this.shoplist = res.data.data.data;
            },
        });
    },
    methods: {
        ...mapMutations(["updateUserItem"]),
        async initIndex() {
            let { id = 0 } = this.options;
            if (!id) return;
            let data = await this.$api.dynamic.coachDynamicInfo({
                id,
            });
            console.log(data, "data");
            this.cate_id = data.cate_id;
            this.catename = data.cate_name;
            this.shopid = data.goods_id;
            this.shopname = data.goods_name;
            data.cover = [
                {
                    path: data.cover,
                },
            ];
            data.imgs = data.imgs.map((item) => {
                return {
                    path: item,
                };
            });

            for (let key in this.subForm) {
                this.subForm[key] = data[key];
            }
        },
        imgUpload(e) {
            let { imagelist, imgtype } = e;
            this.subForm[imgtype] = imagelist;
        },
        // 选择地区
        async toChooseLocation(e) {
            await this.$util.checkAuth({
                type: "userLocation",
            });
            let { lat: locaLat = "", lng: locaLng = "" } = this.location;
            let { id = 0, lat: addrLat, lng: addrLng } = this.subForm;

            if (id) {
                locaLat = addrLat;
                locaLng = addrLng;
            }

            let param = {};
            if (!locaLat && !locaLng) {
                // #ifdef H5
                if (this.$jweixin.isWechat()) {
                    this.$util.showLoading();
                    await this.$jweixin.wxReady2();
                    let { latitude, longitude } = await this.$jweixin.getWxLocation();
                    locaLat = latitude;
                    locaLng = longitude;
                }
                // #endif
                // #ifdef APP-PLUS
                let location = await this.$util.getBmapLocation();
                locaLat = location.lat;
                locaLng = location.lng;
                // #endif
            }

            // #ifndef MP-WEIXIN
            param = {
                latitude: locaLat,
                longitude: locaLng,
            };
            // #endif
            let [, { address = "", longitude: lng, latitude: lat }] = await uni.chooseLocation(
                param
            );
            if (!lng) return;
            this.subForm.address = address;
            this.subForm.lat = lat;
            this.subForm.lng = lng;
        },
        //表单验证
        validate(param) {
            let validate = new this.$util.Validate();
            this.rule.map((item) => {
                let { name } = item;
                validate.add(param[name], item);
            });
            let message = validate.start();
            return message;
        },
        async submit() {
            let subForm = this.$util.deepCopy(this.subForm);
            subForm.cate_id = this.cate_id;
            subForm.goods_id = this.shopid;
            subForm.shop_id = uni.getStorageSync("shop_id");
            console.log(subForm);
            subForm.imgs =
                subForm.imgs && subForm.imgs.length > 0
                    ? subForm.imgs.map((item) => {
                          return item.path;
                      })
                    : [];
            let url =
                subForm.type == 1
                    ? subForm.imgs.length > 0
                        ? subForm.imgs[0]
                        : ""
                    : subForm.cover && subForm.cover.length > 0
                    ? subForm.cover[0].path
                    : "";
            (subForm.cover = url ? url : ""), console.log(subForm.cover, "subForm.cover");
            let msg = this.validate(subForm);
            if (msg) {
                this.$util.showToast({
                    title: msg,
                });
                return;
            }
            if (this.lockTap) return;
            this.lockTap = true;

            this.$util.showLoading();
            try {
                let methodModel = subForm.id ? "dynamicUpdate" : "dynamicAdd";
                let { status = 1 } = await this.$api.dynamic[methodModel](subForm);
                this.$util.hideAll();
                this.$util.showToast({
                    title: status == 1 ? "正在审核中" : subForm.id ? `编辑成功` : `发布成功`,
                });
                this.updateUserItem({
                    key: "haveShieldOper",
                    val: 1,
                });
                setTimeout(() => {
                    // this.$util.back()
                    // this.$util.goUrl({
                    // 	url: 1,
                    // 	openType: `navigateBack`
                    // })
                    uni.navigateBack({
                        delta: 1,
                    });
                }, 2000);
            } catch (e) {
                setTimeout(() => {
                    this.lockTap = false;
                    this.$util.hideAll();
                }, 2000);
            }
        },
        change(e) {
            let curMultiIndex = e.detail.value;
            if (curMultiIndex[0] != this.multiIndex[0]) {
                this.multiIndex = [curMultiIndex[0], 0, 0];
            } else if (curMultiIndex[1] != this.multiIndex[1]) {
                this.multiIndex = [this.multiIndex[0], curMultiIndex[1], 0];
            } else if (curMultiIndex[2] != this.multiIndex[2]) {
                this.multiIndex = [this.multiIndex[0], this.multiIndex[1], curMultiIndex[2]];
            }
            console.log(this.multiIndex);
            var i = this.multiIndex[0];
            var j = this.multiIndex[1];
            var k = this.multiIndex[2];
            this.catelist2 = this.catelist1[i].children;

            console.log(this.cateid);
        },
        cateSubmit() {
            var i = this.multiIndex[0];
            var j = this.multiIndex[1];
            if (this.catelist2.length) {
                this.catename = this.catelist1[i].title + "," + this.catelist1[i].children[j].title;
                this.cate_id = this.catelist1[i].children[j].id;
            } else if (this.catelist1.length) {
                this.catename = this.catelist1[i].title;
                this.cate_id = this.catelist1[i].id;
            }

            this.is_cate_show = false;
        },
        choseShop(e) {
            this.shopname = this.shoplist[e.detail.value].title;
            this.shopid = this.shoplist[e.detail.value].id;
        },
    },
};
</script>

<style lang="scss">
@import url(@/components/common.css);
page {
    background: #fff;
}

.dynamic-technician-add {
    .icon-dingwei {
        font-size: 28rpx;
    }

    .icongengduo {
        font-size: 26rpx;
        color: #9b9b9b;
    }

    .textarea {
        width: 690rpx;
    }
}
.layer {
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.7);
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

.layer-content {
}

/* 浮层内容 */
.confirm-bar {
    position: fixed;
    bottom: 600rpx;
    left: 0;
    width: 750rpx;
}

.line-height-80 {
    height: 80rpx;
    line-height: 80rpx;
}

.padding-lr-30 {
    padding-left: 30rpx;
    padding-right: 30rpx;
}

.bg-ff {
    background: #fff;
}

.border-bottom-ed {
    border-bottom: 1rpx solid #ededed;
}

.flex {
    display: flex;
}

.align-center {
    align-items: center;
}

.justify-between {
    justify-content: space-between;
}

.picker-view {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 750rpx;
    height: 600rpx;
    background: #fff;
}

.item-pircker {
    line-height: 80rpx;
    height: 80rpx;
    align-items: center;
    justify-content: center;
    text-align: center;
}
</style>
